package org.lgiavedoni.android.franq.util.phone.voice;

import java.util.ArrayList;
import java.util.List;

import org.lgiavedoni.android.franq.service.config.ConfigService;
import org.lgiavedoni.android.franq.service.config.ConfigService.ConfigKey;
import org.lgiavedoni.android.franq.service.phone.ContextService;
import org.lgiavedoni.android.franq.util.phone.ActivityUtil;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;

public class VoiceRecognition extends Activity {

	private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
	private static VoiceReceiver vr;

	/**
	 * Called with the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Check to see if a recognition activity is present
		PackageManager pm = getPackageManager();
		List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
		if (activities.size() != 0) {
			startVoiceRecognitionActivity();
		} else {
			// "Recognizer not present");
		}
	}

	/**
	 * Fire an intent to start the speech recognition activity.
	 */
	private void startVoiceRecognitionActivity() {
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
		startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
	}

	/**
	 * Handle the results from the recognition activity.
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
			ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
			if (vr != null)
				vr.result(matches);
		} else {
			// do nothing
		}

		super.onActivityResult(requestCode, resultCode, data);
		finish();
	}

	public static void recognizeSpeech(VoiceReceiver vr) {
		if (ContextService.inst.isApplicationContextLoaded() && ConfigService.inst.getValueAsBoolean(ConfigKey.VOICE_RECOGNITION)) {
			VoiceRecognition.vr = vr;
			ActivityUtil.startActivity(VoiceRecognition.class);
		}
	}
}